<template>
  <div>
    <!-- 品牌管理模块 -->
    <!-- 添加按钮 -->
    <el-button type="primary" icon="el-icon-plus" style="margin: 15px 0" @click="showdialog">添加</el-button></el-button>
    <!-- 表格 -->
    <el-table :data="pageData" style="width: 100%;" border>
      <el-table-column type="index" label="序号" width="80px;"></el-table-column>
      <el-table-column prop="tmName" label="品牌名称" width="width"></el-table-column>
      <el-table-column prop="logoUrl" label="品牌Logo" width="width">
        <template slot-scope="scope">
          <img :src="scope.row.logoUrl" alt="" style="width:40px; height: 40px;">
        </template>
      </el-table-column>
      <el-table-column prop="prop" label="操作" width="width">
        <template slot-scope="scope">
          <el-button type="warning" icon="el-icon-edit" size="mini" @click="updateTrademark(scope.row)">修改</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteTrademark(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="getPageList"
      style="margin-top: 15px; text-align: center;"
      :current-page="page"
      :page-size="limit"
      :page-sizes="[3, 5, 10, 20]"
      layout="sizes, prev, pager, next, jumper, total "
      :total="total">
    </el-pagination>

  <!-- 添加，修改弹框 -->
  <el-dialog :title="tmform.id ? '修改品牌' : '添加品牌'" :visible.sync="dialogFormVisible">
    <el-form style="width: 80%" :model="tmform" :rules="rules" ref="tmform">
      <el-form-item label="商品名称" label-width="100px" prop="tmName">
        <el-input autocomplete="off" v-model="tmform.tmName"></el-input>
      </el-form-item>
      <el-form-item label="商品Logo" label-width="100px" prop="logoUrl">
        <!-- 收集表单不能用v-mode，并不是表单元素 -->
        <el-upload
          class="avatar-uploader"
          action="/dev-api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <i v-if="!tmform.logoUrl" class="el-icon-plus avatar-uploader-icon"></i>
          <div v-else>
            <img :src="tmform.logoUrl" class="avatar">
            <i
              class="el-icon-delete detImg"
              @click.stop="handleImgRemove()"
            />
          </div>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="addOrUpdateTrademark">确 定</el-button>
    </div>
  </el-dialog>
  </div>
</template>

<script>
export default {
  name: "TradeMark",
  data() {
    //自定义校验规则
    var validateTmName = (rule, value, callback) => {
      if (value.length < 2 || value.length > 10) {
        callback(new Error("品牌名称2-10位"));
      } else {
        callback();
      }
    }
    return {
      page: 1,
      limit: 3,
      total: 0,
      pageData: [],
      dialogFormVisible: false,
      tmform: {
        logoUrl: '',
        tmName: '',
      },
      rules: {
        tmName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          // { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'change' }
          // 自定义校验规则
          { validator: validateTmName, trigger: 'change' }
        ],
        logoUrl: [
          { required: true, message: '请选择品牌图片', trigger: 'change'}
        ],
      },
    };
  },
  mounted() {
    this.getPageList();
  },
  methods: {
    // 获取分页列表，当前第几页
    async getPageList(currentPage = 1) {
      this.page = currentPage;
      const { page, limit } = this;
      const result = await this.$API.tradeMark.reqgetTradeMarkList(page, limit);
      console.log(result);
      if (result.code == 200) {
        this.pageData = result.data.records;
        this.total = result.data.total;
      }
    },
    // 切换展示页数
    handleSizeChange(limit) {
      this.limit = limit;
      this.getPageList();
    },
    // 点击添加品牌
    showdialog(){
      this.dialogFormVisible = true
      // 清空表单
      this.tmform = {logoUrl: '', tmName: '',}
    },
    // 修改品牌
    updateTrademark(row){
      this.dialogFormVisible = true
      // 表单信息浅拷贝
      this.tmform = {...row}
    },
    // 上传图片成功
    handleAvatarSuccess(res, file) {
        this.tmform.logoUrl = URL.createObjectURL(file.raw);
    },
    // 上传图片成功之前
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    // 确认按钮，添加或修改
    addOrUpdateTrademark(){
      this.$refs.tmform.validate(async (valid) => {
        if(valid){
          this.dialogFormVisible = false
          let result = await this.$API.tradeMark.reqAddOrUpdateTradeMark(this.tmform)
          if(result.code == 200){
            this.getPageList(this.tmform.id?this.page:1);
            this.$message({type: "success", message: this.tmform.id ? '品牌修改成功' : '品牌添加成功'})
          }
        }else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    // 上传图片后需更改图片,删除当前图片
    handleImgRemove(){
      this.tmform.logoUrl = ''
    },
    // 删除当前品牌信息
    deleteTrademark(row){
       this.$confirm(`确认删除${row.tmName}这个品牌?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(async() => {
          let result = await this.$API.tradeMark.reqDeleteTradeMark(row.id)
          if(result.code == 200){
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }
          this.getPageList(this.pageData.length > 1 ? this.page : this.page - 1)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
  },
};
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .detImg {
      position: absolute;
      top: 0;
      right: 0;
      font-size: 20px;
      cursor: pointer;
    }
</style>
<style scoped>
</style>